import * as THREE from "../../../modules/three/three.module.js";
import { toFixedVector } from '../lib/util/StaticMethods.js';

const quat = new THREE.Quaternion();
const mat = new THREE.Matrix4();

export default class Blocking {
  position = new THREE.Vector3();
  rotation = new THREE.Euler();
  scale = new THREE.Vector3(1, 1, 1);

  constructor(
    position = new THREE.Vector3(),
    rotation = new THREE.Euler(),
    scale = new THREE.Vector3(1, 1, 1),
  ) {
    this.position.copy(position);
    this.rotation.copy(rotation);
    this.scale.copy(scale);
  }

  initByObb(obb) {
    this.position.copy(obb.center);
    this.scale.copy(obb.halfSize).multiplyScalar(2);
    this.rotation.setFromRotationMatrix(new THREE.Matrix4().setFromMatrix3(obb.rotation));
    return this;
  }

  getCorners(eightPoints) {
    const [v0, v1, v2, v3, v4, v5, v6, v7] = eightPoints;
    quat.setFromEuler(this.rotation);
    mat.compose(this.position, quat, this.scale);
    const h = 0.5;
    v0.set(-h, h, h);
    v1.set(h, h, h);
    v2.set(h, h, -h);
    v3.set(-h, h, -h);
    v4.set(-h, -h, h);
    v5.set(h, -h, h);
    v6.set(h, -h, -h);
    v7.set(-h, -h, -h);
    eightPoints.forEach(it => it.applyMatrix4(mat));
    return eightPoints;
  }

  toJsonObj() {
    const obj = {};
    obj.position = toFixedVector(this.position, 3).toArray();
    obj.rotation = toFixedVector(this.rotation, 3).toArray();
    obj.scale = toFixedVector(this.scale, 3).toArray();
    return obj;
  }

  fromJsonObj(jsonObj) {
    this.position.fromArray(jsonObj.position);
    this.rotation.fromArray(jsonObj.rotation);
    this.scale.fromArray(jsonObj.scale);
    return this;
  }
}
